<?php

class CategoryService extends \BaseService{

    /**
     * 获得全部栏目
     * @return [array] [栏目名，模型名，模型id]
     * $categories['categoryId']    栏目id
     * $categories['categoryName']  栏目名
     * $categories['modelId']       模型id
     * $categories['modelName']     模型名
     */
    public static function index(){
        $categories = Category::all();
        $categoryArray = array();
        for($i=0; $i<count($categories); $i++){
            $model = Model::find($categories[$i]['model_id']);
            if(!isset($model)){
                throw new ModelNoFoundException;
            }
            $categoryArray[$i]['categoryId'] = $categories[$i]['id'];
            $categoryArray[$i]['categoryName'] = $categories[$i]['category_name'];
            $categoryArray[$i]['modelId'] = $model['id'];
            $categoryArray[$i]['modelName'] = $model['model_name'];
        }
        return $categoryArray;
    }

    /**
     * 增加栏目
     * @param [string] $categoryName    栏目名
     * @param [int]    $modelId         所用模型id
     */
    public static function add($data){
        try{
            DB::transaction(function() use ($data){
                $category = new Category;
                $category->name = $data['name'];
                $category->model_Id = $data['modelId'];
                $category->save();
            });
        }catch(Exception $e){
            throw new CategoryAddException;
        }
        return self::getResult('成功添加栏目');
    }

    /**
     * 更新栏目
     * @param  [array] $category [栏目id，栏目名，栏目所用模型id]
     * @return [array]       [异常信息]
     */
    public static function update($data){
        try{
            DB::transaction(function() use ($data){
                $category = Category::find($data['id']);
                
                if(!isset($category)){
                    throw new NoCategoryException;
                }
                $category->name = $data['name'];
                $category->model_Id = $data['modelId'];
                $category->save();
            });
        }catch(Exception $e){
            throw new CategoryUpdateException;
        }
        return self::getResult('成功更新栏目');
    }

    /**
     * 删除栏目
     * @param  [int] $categoryId [栏目id]
     * @return [array]             [异常信息]
     */
    public static function delete($id){
        try{
            $category = Category::find($id);
            if(!isset($category)){
                throw new NoCategoryException;
            }
            $modelName = Model::where('id', $category['model_id'])->pluck('table_name');
            if(!isset($modelName)){
                throw new NoModelException;
            }
            $model = studly_case($modelName);
            $documents = $model::where('id', $id)->delete();
            $category->delete();
        }catch(Exception $e){
            throw new CategoryDeleteException;
        }
        return self::getResult('成功删除栏目');
    }

}